package com.y.mytest.collection;

import com.y.mytest.entity.Fruits;
import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**
 * @ClassName: MyStream
 * @author: 叶子豪
 * @create: 2021-01-25 14:42
 */
public class StreamList {

    Fruits apple1 = new Fruits(1, "苹果1", new BigDecimal("3.25"), 10);
    Fruits apple2 = new Fruits(1, "苹果2", new BigDecimal("1.35"), 20);
    Fruits banana = new Fruits(2, "香蕉", new BigDecimal("2.89"), 30);
    Fruits litchi = new Fruits(3, "荔枝", new BigDecimal("9.99"), 40);
    List<Fruits> appleList = new ArrayList<Fruits>() {{
        add(apple1);
        add(apple2);
        add(banana);
        add(litchi);
        //add(null);
    }};

    @Test
    public void test1() {
        Stream<Integer> stream = Stream.of(6, 4, 6, 7, 3, 9, 8, 10, 12, 14, 14);
        Stream<Integer> newStream = stream.filter(s -> s > 5) //6 6 7 9 8 10 12 14 14
                .distinct() //6 7 9 8 10 12 14
                .skip(2) //9 8 10 12 14
                .limit(2); //9 8
        newStream.forEach(System.out::println);
    }

    @Test
    public void listToMap() {
        Map<Integer, List<Fruits>> groupBy = appleList.stream().collect(Collectors.groupingBy(Fruits::getId));
        System.out.println("groupBy:" + groupBy);

        Map<Integer, Fruits> appleMap = appleList.stream().collect(Collectors.toMap(Fruits::getId, a -> a, (k1, k2) -> k2));
        System.out.println("groupBy:" + appleMap);

    }

    @Test
    public void arrayToList() {
        Integer[] myArray = {1, 2, 3};
        List myList = Arrays.stream(myArray).collect(Collectors.toList());
        int[] myArray2 = {1, 2, 3};
        myList = Arrays.stream(myArray2).boxed().collect(Collectors.toList());
    }

    @Test
    public void filterList() {
        List<Fruits> filterList = appleList.stream().filter(a -> !a.getName().equals("香蕉")).collect(Collectors.toList());
        System.err.println("filterList:" + filterList);
    }

    @Test
    public void totalMoney() {
        BigDecimal totalMoney = appleList.stream().map(Fruits::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        System.err.println("totalMoney:" + totalMoney);
    }

    @Test
    public void 去重() {
        List<Fruits> unique = appleList.stream().collect(
                collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(Fruits::getId))), ArrayList::new)
        );
        System.out.println(unique);
    }
}
